# -*- coding: utf-8 -*-

from osv import fields,osv
from osv.orm import browse_record
import tools
from functools import partial
import pytz
import pooler
from tools.translate import _
from service import security
import netsvc

class aas_study_result_detail(osv.TransientModel):
    _name = 'aas.study.result.detail'
    _columns = {
        'result_id': fields.many2one('aas.study.result', string='Study Result', required=False),
        'name': fields.char('/', size=8),
        'year': fields.char('Năm học', size=64),
        'semester': fields.char('Học kỳ', size=64),
        'subject_code': fields.char('Mã môn học', size=64),
        'subject_name': fields.char('Tên môn học', size=64),
        'th_credit': fields.integer('Số tín chỉ lý thuyết'),
        'pr_credit': fields.integer('Số tín chỉ thực hành'),
        'total_credit': fields.integer('Tổng số tín chỉ'),
        'mark': fields.float('Điểm trung bình', digits=(16,2)),
        'note': fields.char('Ghi chú', size=64),
        'does_pass': fields.boolean('Hoàn thành?'),
    }
    _defaults = {
        'name': lambda *a: '/',
    }
aas_study_result_detail()

class aas_study_result(osv.TransientModel):
    _name = 'aas.study.result'
    _description = 'Kết quả học tập'
    _columns = {
        'student_id': fields.many2one('res.users', string='Sinh viên', domain=[('type', '=', 'student')], required=True),
        'type': fields.selection([('full', _('Đầy đủ')), ('compact', _('Tiêu chuẩn'))], string='Phiên bản', required=True),
        'year': fields.many2one('aas.academic.year', string='Năm học'),
        'semester': fields.many2one('aas.academic.semester', string='Học kỳ'),
        'readonly': fields.boolean('Readonly'),
        'details': fields.one2many('aas.study.result.detail', 'result_id', string='Chi tiết', readonly=True),
        'gpa': fields.float('Điểm trung bình chung', digits=(16,2), readonly=True),
        'total_credit': fields.integer('Tổng số tín chỉ đã tích lũy', readonly=True),
    }
    _defaults = {
        'type': lambda *a: 'full',
    }
    _order = 'year,semester'
    
    def compute(self, cr, uid, id, context=False):
        res = {}
        user_obj = self.pool.get('res.users')
        detail_obj = self.pool.get('aas.study.result.detail')
        
        year_id = False
        semester_id = False
        type = 'full'
        student_id = uid
        
        if id:
            obj = self.browse(cr, uid, id, context=context)
        
            year_id = obj.year and obj.year.id or False
            semester_id = obj.semester and obj.semester.id or False
            type = obj.type
            student_id = obj.student_id.id or uid
        
        all_details = detail_obj.search(cr, uid, [])
        detail_obj.unlink(cr, uid, all_details)
        
        study_results = user_obj.get_study_result(cr, uid, student_id, year_id, semester_id, type, context=context)
        
        year_obj = self.pool.get('aas.academic.year')
        semester_obj = self.pool.get('aas.academic.semester')
        
        all_year_names = study_results['details'].keys()
        all_year_ids = year_obj.search(cr, uid, [('name', 'in', all_year_names)])
        all_years = []
        new_details = {}
        for year in year_obj.browse(cr, uid, all_year_ids, context=context):
            all_years.append([year.name, year.id])


        details = []
        for year_name, year_id_new in all_years:
            semester_names = study_results['details'][year_name].keys()
            semesters = []
            all_semester_ids = semester_obj.search(cr, uid, [('number', 'in', semester_names), ('academic_year', '=', year_id_new)])
            for semester in semester_obj.browse(cr, uid, all_semester_ids):
                semesters.append(semester.name)
            for semester_name in semesters:
                for line in study_results['details'][year_name][semester_name]:
                    detail_data = {
                        'year': line[0],
                        'semester': line[1],
                        'subject_code': line[2],
                        'subject_name': line[3],
                        'th_credit': line[4],
                        'pr_credit': line[5],
                        'total_credit': line[6],
                        'mark': line[7],
                        'note': line[8],
                        'does_pass': line[9],
                    }
                    details.append(detail_data)
        details.reverse()
        gpa = study_results.get('gpa', 0.00)
        total_credit = study_results.get('total_credit', 0)
        res.update({'details': details, 
                    'student_id': student_id, 
                    'year': year_id, 
                    'semester': semester_id, 
                    'gpa': gpa, 
                    'type': type,
                    'total_credit': total_credit})
        return res
    
    
    def default_get(self, cr, uid, fields, context=False):
        res = super(aas_study_result, self).default_get(cr, uid, fields, context=context)
        id = context.get('active_id', False)
        res_compute = self.compute(cr, uid, id, context=context)
        res.update(res_compute)
        res.update({'readonly': True})
        return res
        
    def print_result(self, cr, uid, ids, context=None):
        datas = {}
        obj = self.browse(cr, uid, ids[0], context=context)
        
        student_id = obj.student_id and obj.student_id.id or uid
        year_id = obj.year and obj.year.id or False
        semester_id = obj.semester and obj.semester.id or False
        type = 'compact'
        
        user_obj = self.pool.get('res.users')
        
        study_results = user_obj.get_study_result(cr, uid, student_id, year_id, semester_id, type, context=context)
        
        datas['model'] = 'res.users'
        datas['id'] = student_id
        datas['ids'] = [student_id]
        return {
            'type': 'ir.actions.report.xml', 
            'report_name': 'aas_study_result_report', 
            'datas': datas,
            'context': {'study_results': study_results, 'student_id': student_id},
        }
    
    def update_result(self, cr, uid, ids, context=None):
        return {
            'name': _('Chi tiết kết quả học tập'),
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'aas.study.result',
            'type': 'ir.actions.act_window',
            'target': 'new',
        }
aas_study_result()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
